package com.cskaoyan.login;

import com.cskaoyan.utils.JDBCUtils;

import java.sql.*;

/**
 * 创建日期: 2022/11/17 11:03
 *
 * @author ciggar
 *
 * 登录的案例
 *
 * 演示数据库的注入问题
 */
public class LoginDemo {

    public static void main(String[] args) throws SQLException {

        // 常规调用
//        Boolean ret = loginUsePreparedStatement("天明", "UPAN");
//
//        if (ret) {
//            System.out.println("登录成功！");
//        }else {
//            System.out.println("登录失败！");
//        }

        // SQL注入的调用
        // select * from user where username = '' and password = ''
        // select * from user where username = 'xxx' and password = 'asdad'  or '1=1';

        Boolean ret = loginUsePreparedStatement("xxx","asdad'  or '1=1");
        if (ret) {
            System.out.println("登录成功！");
        }else {
            System.out.println("登录失败！");
        }

    }


    // statement
    // 登录的方法
    public static Boolean login(String username,String password) throws SQLException {

        // 根据用户名和密码去查询用户
        Connection connection = JDBCUtils.getConnection();
        Statement statement = connection.createStatement();

        String sql = "select * from user where username = '"+username+"'  and password = '" + password + "'";
        System.out.println(sql);

        ResultSet resultSet = statement.executeQuery(sql);
        // 如果查到了用户，说明用户名和密码正确，那么登录成功
        if (resultSet.next()) {
            return true;
        }
        // 如果没有查到用户，那么登录失败
        else {
            return false;
        }
    }


    // PreparedStatement
    // 登录的方法，是安全的
    public static Boolean loginUsePreparedStatement(String username,String password) throws SQLException {

        //1. 获取连接
        Connection connection = JDBCUtils.getConnection();

        // 2. 创建PreparedStatement对象
        PreparedStatement preparedStatement = connection.prepareStatement("select * from user where username = ? and password = ?");


        // 3. 封装参数
        preparedStatement.setString(1,username);
        preparedStatement.setString(2,password);

        // 4. 传递参数，执行SQL语句
        ResultSet resultSet = preparedStatement.executeQuery();


        // 返回结果
        if (resultSet.next()) {
            return true;
        }
        else {
            return false;
        }


    }
}
